/**
 * shader/xxx
 * 着色器 aurora 控制器
 * 
 * 这是我第一个按了直接生效的, 就是不需要按提交按钮的
 * 
 * @author Zdream
 * @since aurora 0.4.0
 */

function create (context) {
  return {
    template : context.template,
    data : function () {
      return {
        status : null,
        dirty : false,
        checkHandler : 0,
        
        speed : 1,
      };
    },
    props : {
      sid : String,
    },
    methods : {
      onPlay : function () {
        context.sendCommand(this.sid, 'set_speed', {
          speed : this.speed
        });
      },
      onPause : function () {
        context.sendCommand(this.sid, 'pause', null);
      },
      afterSetSpeed : function () {
        this.dirty = true;
      },

      checkAndSubmit : function () {
        if (!this.dirty) {
          return;
        }
        if (this.speed != this.status.data.speed) {
          context.sendCommand(this.sid, 'set_speed', {
            speed : this.speed
          });
        }
        this.dirty = false;
      },

      overrideData : function () {
        if (this.status && this.status.data) {
          let source = this.status.data;

          this.speed = source.speed;
        }
      },

      // 监听事件部分
      onScreenUpdated : function () {
        this.status = context.getStatus(this.sid);
        if (!this.dirty) {
          this.overrideData();
        }
      }
    },
    mounted : function () {
      this.onScreenUpdated();
      
      context.getBus().$on('screen-status-sync-all', this.onScreenUpdated);
      context.getBus().$on('screen-updated', this.onScreenUpdated);
      context.getBus().$on('screen-destroyed', this.onScreenUpdated);

      this.checkHandler = setInterval(() => this.checkAndSubmit(), 100);
    },
    destroyed : function () {
      context.getBus().$off('screen-status-sync-all', this.onScreenUpdated);
      context.getBus().$off('screen-updated', this.onScreenUpdated);
      context.getBus().$off('screen-destroyed', this.onScreenUpdated);

      clearInterval(this.checkHandler);
    }
  }
}

export default create;
